axios.defaults.baseURL = 'http://hmajax.itheima.net';
axios.interceptors.request.use(function (config) {
    // console.log('请求发送之前：拦截器',config);
    const token = localStorage.getItem('my-token')
    if (token) {
        config.headers.Authorization = token
    }
    return config;
}, function (error) {
    return Promise.reject(error);
})
axios.interceptors.response.use(function (response) {
    console.log('响应成功拦截器',response);
    return response.data;
},function (error) {
    // console.log('响应错误拦截器')
    console.dir(error)
    if(error.response.status === 401){
        logout()
    }
    return Promise.reject(error);
})
//封装轻提示函数
function showToast(message) {
    const toastEl = document.querySelector('.my-toast')
    const toast = new bootstrap.Toast(toastEl)
    document.querySelector('.toast-body').innerHTML = message
    toast.show()
}
function checkLogin() {
    const token = localStorage.getItem('my-token')
    if (!token) {
        showToast('请先登录')
        setTimeout(() => {
            location.href = './login.html'
        }, 800)
    }
}
function render() {
    const useer = document.querySelector('.username')
    const user = localStorage.getItem('my-username')
    useer.innerHTML = user
}

function logout() {
    localStorage.removeItem('my-token')
    localStorage.removeItem('my-username')
    showToast('退出成功')
    setTimeout(() => {
        location.href = './login.html'
    })
}
